<template>
  <div class="main-container">
    <div class="searchBox">
      <img src="/img/search.png" alt="">
      <input v-model="query.key_word" type="text" placeholder="搜索" @keyup.enter="handleSearch">
    </div>
    
    

    <div class="listBox">
      <ul class="menuBox">
        <li :class="item.group_id === query.group_id ? 'menu active' : 'menu'" v-for="(item, index) in groupList" :key="index" v-on:click="handleClick(item)">{{ item.name }}</li>
      </ul>
      <div class="menuListBox">
        <el-row>
          <el-col :span="8" v-for="(prod, index) in prodList" :key="index" >
            <el-card :body-style="{ padding: '0px' }" style="margin:10px" >
              <a href="javascript:;" @click="openDetail(prod)">
                <img :src="prod.img" style="width:100%;height:200px;display:block;object-fit:cover;" />
              </a>
              <div style="padding: 14px;height:95px;">
                <div style="font-size: 18px;text-align: left;">{{ prod.title }}</div>
                <div style="font-size: 12px;text-align: left;color: grey;">{{ prod.info }}</div>
                <div style="text-align: left;min-height:20px">
                  <el-tag size="mini" class="tag" v-for="(sale, idx) in prod.saleList" :key="idx">{{ sale.title }}</el-tag>
                </div>
                <div class="bottom">
                  <div class="price">
                    <span class="n_price">¥{{ prod.n_price }}</span>
                    <span v-if="prod.o_price" class="o_price">¥{{ prod.o_price }}</span>
                  </div>
                  <div class="cart-but">
                    <el-button-group>
                      <el-button icon="el-icon-shopping-cart-2" size="mini" type="warning" @click="handleCart(prod)"></el-button>
                      <el-button size="mini" type="danger" @click="handleOrderCreate(prod)">立即购买</el-button>
                    </el-button-group>
                    
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog title="订单确认" :visible.sync="openOrderDialog" >
      <el-form ref="orderForm" label-position="top" :model="orderForm" :rules="orderRules">
        <el-form-item prop="addr_id">
          <el-select v-model="orderForm.addr_id" placeholder="请选择收货地址" style="width:100%" >
            <el-option
              style="height: 100px;"
              v-for="addr in addrList"
              :key="addr.addr_id"
              :label="addr.name + addr.phone_number"
              :value="addr.addr_id">
              <el-row>
                <el-col :span="12">
                  <span style="float: left">{{ addr.name }}</span>
                </el-col>
                <el-col :span="12">
                  <span style="float: right">{{ addr.phone_number }}</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <span>{{ addr.address }}</span>
                </el-col>
              </el-row>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :span="8">
              <img :src="orderForm.prod.img" style="width:100%;display:block;height: 150px;"/>
            </el-col>
            <el-col :span="16">
              <div style="padding: 14px;">
                <div style="font-size: 18px;text-align: left;line-height: 10px;">{{ orderForm.prod.title }}</div>
                <div style="font-size: 12px;text-align: left;color: grey;">{{ orderForm.prod.info }}</div>
                <div style="text-align: left;">
                  <el-tag size="mini" class="tag">618大促</el-tag>
                  <el-tag size="mini">满100减10</el-tag>
                </div>
                <div class="bottom">
                  <div class="price">
                    <span class="n_price">¥{{ orderForm.prod.n_price }}</span>
                    <span v-if="orderForm.prod.o_price" class="o_price">¥{{ orderForm.prod.o_price }}</span>
                  </div>
                  <div class="cart-but">
                    <el-input-number v-model="orderForm.prod.amount" :min="1" size="mini" @change="handleOrderAmount"></el-input-number>      
                  </div>
                </div>
              </div>
              
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div style="line-height:40px;font-weight: bold;color:#065b2b;text-align: right;">合计{{ orderForm.price }}￥</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitOrderForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="支付" :visible.sync="openPayDialog" @close="handlePaid">
      <img style="margin: auto;display: block;" :src="payForm.qrcode"/>
      <div style="text-align: center;font-size: 40px;font-weight: bold;color: #065b2b;">{{ payForm.price }} ¥</div>
    </el-dialog>
  </div>
</template>
<script>
import { listProdItem, listProdGroup } from '@/api/product'
import { addCart } from '@/api/cart'
import { listAddr } from '@/api/addr'
import { createOrder, payOrder, paidOrder } from '@/api/order'

export default  {
  name: 'Product',
  data () {
    return {
      query: {
        group_id: null,
        key_word: null,
      },
      groupId: null,
      groupList: null,
      prodList: null,
      openOrderDialog: false,
      openPayDialog: false,
      addrList: [],
      orderForm: {
        prod: {},
      },
      orderRules: {
        addr_id: [
          { required: true, message: '请选择收获地址', trigger: 'blur' }
        ]
      },
      payForm: {},
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.getProdList()
      this.groupList = []
      this.groupList.push({ group_id: null, name: "全部" })
      listProdGroup().then(response => {
        for (const group of response.data) {
          this.groupList.push(group)
        }
      })
      console.log(this.groupList)
    },
    getProdList() {
      this.prodList = []
      listProdItem(this.query).then(response => {
        this.prodList = response.data
      })
      // 修改选中的group
    },
    handleClick(item) {
      this.query.group_id = item.group_id
      this.getProdList()
      console.log(item)
    },
    handleSearch() {
      console.log(this.query.key_word)
      this.getProdList()
    },
    openDetail(prod) {
      const prod_id = prod.prod_id
      this.$router.push({
        path: '/product/' + prod_id + '/detail'
      })
    },
    handleCart(prod) {
      const data = { prod_id: prod.prod_id }
      addCart(data).then(response => {
        console.log(response)
        if (response.code === 200) {
          this.$message({
          message: "添加成功",
          type: 'success',
          duration: 1000
        })
        }
      })
    },
    cancel() {
      this.openOrderDialog = false
      this.orderForm = {
        prod: {
          prod_id: null,
          title: null,
          info: null,
          img: null,
          n_price: null,
          o_price: null,
          amount: 1,
          price: null,
        },
        addr_id: null,
        price: null,
      }
    },
    getAddrList() {
      listAddr().then(res => {
        this.addrList = res.data
        for (const addr of this.addrList) {
          if (addr.is_default === 1) {
            this.orderForm.addr_id = addr.addr_id
          }
        }
      })
    },
    handleOrderAmount(value) {
      const n_price = this.orderForm.prod.n_price
      const amount = this.orderForm.prod.amount
      const price = n_price * amount
      this.orderForm.price = price
    },
    handleOrderCreate(prod) {
      const prod_id = prod.prod_id
      const title = prod.title
      const info = prod.info
      const img = prod.img
      const n_price = prod.n_price
      const o_price = prod.o_price
      this.orderForm = {
        prod: {
          prod_id: prod_id,
          title: title,
          info: info,
          img: img,
          n_price: n_price,
          o_price: o_price,
          amount: 1,
          price: n_price,
        },
        addr_id: null,
        price: n_price,
      }
      this.getAddrList()
      this.openOrderDialog = true
    },
    submitOrderForm() {
      this.$refs['orderForm'].validate((valid) => {
        if (valid) {
         createOrder(this.orderForm).then(res => {
            if (res.code === 200) {
              this.openOrderDialog = false
              const order_id = res.data.order_id
              console.log('order_id: ', order_id)
              this.handleOrderPay(order_id)
            } else {
              this.$message({
                message: res.msg,
                type: 'error',
                duration: 300
              })
            }
          })
        }
      })
    },
    handleOrderPay(order_id) {
      payOrder(order_id).then(res => {
        if (res.code === 200) {
          this.payForm = res.data
          this.openPayDialog = true
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            duration: 300
          })
        }
      })
    },
    handlePaid() {
      this.$confirm('是否已完成支付', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paidOrder(this.payForm.order_id).then(res => {
          this.$router.push({path: '/me'})
        })
      }).catch(() => {});
    },
  }
}
</script>
<style>
.bottom {
  margin-top: 5px;
  height: 30px;
  position:relative;
  bottom: 0;
}
.price {
  color: #ee554a;
  font-size: 12px;
  position: absolute;
  left: 0;
}
.n_price {
  font-size: 22px;
  font-weight: 700;
  
}
.o_price {
  text-decoration: line-through;
}
.cart-but {
  
  position: absolute;
  right: 0;
}
.tag {
  margin-right: 5px;
}
</style>
